<template>
  <NModal v-model:show="dialogFormVisible" @updateShow="showChange">
    <div class="vip-pop">
      <div class="header">
        <div class="user">
          <n-avatar round :size="avatarSize" :src="userInfo.avatar" />
          <span>充值账号：{{ userInfo.nickname }}</span>
        </div>
        <div class="close-icon" @click="close()">
          <i class="esayIcon esayIcon-youjiantou"></i>
        </div>
      </div>
      <div class="con">
        <div class="package flex">
          <div
            class="package-card"
            :class="{
              'package-card-active': item.id === queryForm.vipSettingId
            }"
            v-for="item in vipList"
            :key="item.id"
            @click="vipChange(item)"
          >
            <div class="youhui" v-if="item.isOverflow">
              <img src="@/assets/icon/youhui.png" alt="" />
              <span>超值优惠</span>
            </div>
            <div class="title">
              <template v-if="item.sendYear">
                <span>买{{ item.year }}年</span>
                <span class="sent">送{{ item.sendYear }}年</span>
              </template>
              <template v-else>
                <span>{{ item.year }}年</span>
              </template>
            </div>
            <div class="date">到账{{ item.month }}个月</div>
            <div class="price">
              <span>￥</span>
              <span>{{ item.nowPrice }}</span>
            </div>
            <div class="old-price text-through" v-if="item.originalPrice">
              <span>￥</span>
              <span>{{ item.originalPrice }}</span>
            </div>
            <div class="old-price" v-else>
              <span>({{ item.monthPrice }}元/月)</span>
            </div>
          </div>
        </div>
        <div class="type-row">
          <div class="pay-type">
            <div class="card">
              <div class="icon">
                <QrcodeVue
                  v-if="queryForm.wxScanCode"
                  :value="queryForm.wxScanCode"
                  :size="qrCodeSize"
                ></QrcodeVue>
              </div>
              <div class="names">
                <img src="@/assets/icon/pay/weixin.png" alt="" />
                <span>扫码支付</span>
              </div>
            </div>
            <div class="card">
              <div class="icon">
                <QrcodeVue
                  v-if="queryForm.zfScanCode"
                  :value="queryForm.zfScanCode"
                  :size="qrCodeSize"
                ></QrcodeVue>
              </div>
              <div class="names">
                <img src="@/assets/icon/pay/zhifubao.png" alt="" />
                <span>扫码支付</span>
              </div>
            </div>
          </div>
          <div class="price-info">
            <div class="flex" style="align-items: flex-end">
              <div class="price">
                <span>￥</span>
                <span>{{ payPrice }}</span>
              </div>
              <div class="old-price" v-if="price !== payPrice">
                ￥{{ price }}
              </div>
            </div>
            <n-select
              class="select"
              clearable
              v-model:value="queryForm.vipCouponId"
              :options="options"
              @update:value="couponChange"
            >
              <template #empty>
                <div>
                  <span>暂无可使用优惠券</span>
                </div>
              </template>
            </n-select>
            <div class="tips">
              <span>支付即代表你同意</span>
              <span @click="handOpen">《网站用户充值协议》</span>
            </div>
          </div>
        </div>
        <div class="vip-privilege">
          <div class="label">
            <img src="@/assets/icon/pay/vip.png" alt="" />
            <span>尊贵特权</span>
          </div>
          <div class="btns">
            <div class="btn">可下载免费资源30个/天</div>
            <div class="btn">付费资源VIP超值折扣</div>
            <div class="btn">可领取VIP专属优惠券</div>
            <div class="btn">享受VIP专属资源</div>
            <div class="btn">一对一专属客服</div>
            <div class="btn">会员身份标识</div>
          </div>
        </div>
      </div>
      <IllusDia ref="lusRef" />
    </div>
  </NModal>
</template>
<script setup lang="ts">
import { NAvatar, NModal, NSelect } from 'naive-ui'
import { ref, computed, defineAsyncComponent } from 'vue'
import { useWindowSize } from '@vueuse/core/index'
import { useAppsStore } from '@/stores/modules/app'
import { storeToRefs } from 'pinia'
import QrcodeVue from 'qrcode.vue'
const IllusDia = defineAsyncComponent(() => import('@/components/IllusDia.vue'))
const { width } = useWindowSize()
const avatarSize = computed(() => {
  const bili = width.value / 1920
  return Number((34 * bili).toFixed(2))
})

const qrCodeSize = computed(() => {
  const bili = width.value / 1920
  return Number((100 * bili).toFixed(2))
})

const useStore = useAppsStore()
const { getUserInfo: userInfo } = storeToRefs(useStore)
interface queryFormState {
  type: number
  vipCouponId: number | undefined
  vipSettingId: number
  wxScanCode: string
  zfScanCode: string
}
const queryForm = ref<queryFormState>({
  type: 1,
  vipCouponId: undefined,
  vipSettingId: 0,
  wxScanCode: '',
  zfScanCode: ''
})
const options: any = ref([])
interface VipListItem {
  id: number
  isOverflow: boolean
  nowPrice: number
  originalPrice: number
  monthPrice: string
  year: number
  month: number
  sendYear: number
}
const vipList = ref<VipListItem[]>([])
let timer: any = null
const handPay = async () => {
  // const { data } = await systemApi.vipPay({
  //   vipCouponId: queryForm.value.vipCouponId,
  //   vipSettingId: queryForm.value.vipSettingId
  // })
  // queryForm.value.wxScanCode = data.wxScanCode
  // queryForm.value.zfScanCode = data.zfScanCode
  // clearTimer()
  // timer = setTimeout(() => {
  //   payResult(data.id)
  // }, 3000)
}
// const payResult = async (id: string | number) => {
//   const { data } = await systemApi.vipOrderDetail(id)
//   if (data.orderStatus === 'PAID') {
//     toast.success('支付成功')
//     doUserInfo()
//     clearTimer()
//     close()
//     return
//   }
//   clearTimer()
//   timer = setTimeout(() => {
//     payResult(id)
//   }, 3000)
// }
const clearTimer = () => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}
const vipChange = (e: VipListItem) => {
  queryForm.value.vipSettingId = e.id
  getCouList()
}
const lusRef = ref()
const handOpen = () => {
  lusRef.value.open('RECHARGE_AGREEMENT')
}

const dialogFormVisible = ref(false)
const showChange = (e: boolean) => {
  if (!e) {
    close()
  }
}
const close = () => {
  clearTimer()
  dialogFormVisible.value = false
}

const price = computed(() => {
  if (queryForm.value.vipSettingId) {
    const info = vipList.value.find(
      (item: any) => item.id === queryForm.value.vipSettingId
    )
    if (info) {
      return info.nowPrice
    }
  }
  return 0
})
const payPrice = computed(() => {
  if (queryForm.value.vipCouponId) {
    const info = options.value.find(
      (el: any) => el.value === queryForm.value.vipCouponId
    )
    if (info) {
      const total = Number((price.value - info.money).toFixed(2))
      return total >= 0 ? total : 0
    }
  }
  return price.value
})

const couponChange = (e: any) => {
  queryForm.value.vipCouponId = e
  handPay()
}

const getMonthPrice = (year: number, price: number) => {
  const month = year * 12
  const unitPrice = price / month
  return Number(unitPrice.toFixed(2))
}
const open = async (couInfo?: any) => {
  // const { data } = await systemApi.vipList()
  const data = [
    {
      id: 1,
      month: 12,
      monthPrice: 100,
      sendYear: 1,
      year: 1,
      nowPrice: 1200,
      originalPrice: 2400
    }
  ]
  vipList.value = data.map((el: any) => {
    el.month = (el.year + el.sendYear || 0) * 12
    el.monthPrice = getMonthPrice(el.year + el.sendYear || 0, el.nowPrice)
    return el
  })
  if (couInfo && couInfo.isReduction) {
    const starInfo = data.find((el: any) => el.nowPrice >= couInfo.satisfyMoney)
    queryForm.value.vipSettingId = starInfo.id
  } else {
    queryForm.value.vipSettingId = vipList.value[0].id
  }
  getCouList(couInfo ? couInfo.id : null)
  dialogFormVisible.value = true
}
const getCouList = async (id?: null | number) => {
  // const { data } = await systemApi.vipCouList({
  //   money: price.value
  // })
  const data = []
  if (data) {
    options.value = [data].map((el: any) => {
      return {
        label: el.isReduction
          ? `满${el.satisfyMoney}减${el.money}`
          : `${el.money}元无门槛现金券`,
        value: el.id,
        money: el.money
      }
    })
  }
  if (id) {
    queryForm.value.vipCouponId = id
  } else if (queryForm.value.vipCouponId) {
    const isSome = options.value.some(
      (el: any) => el.value === queryForm.value.vipCouponId
    )
    if (!isSome) {
      queryForm.value.vipCouponId = undefined
    }
  }
  handPay()
}
defineExpose({
  open
})
</script>

<style scoped lang="scss">
.vip-pop {
  width: 712px;
  .header {
    height: 90px;
    padding: 0 24px 20px 24px;
    border-radius: 20px 20px 0 0;
    background: linear-gradient(180deg, #f0423d 0%, #922d2b 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    .user {
      display: flex;
      align-items: center;
      span {
        margin-left: 8px;
        font-size: 14px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #ffffff;
      }
    }
    .close-icon {
      cursor: pointer;
      width: 16px;
      height: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        font-size: 20px;
        color: #fff;
      }
      &:hover {
        i {
          color: orangered;
        }
      }
    }
  }
  .con {
    min-height: 400px;
    margin-top: -25px;
    background: #fff;
    border-radius: 20px;
    box-sizing: border-box;
    padding: 34px;
    .package {
      flex-wrap: wrap;
      gap: 20px 23px;
      padding: 17px 36px 0 36px;

      .package-card {
        width: 175px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #dddddd;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-bottom: 25px;
        cursor: pointer;
        position: relative;
        .youhui {
          position: absolute;
          left: -1px;
          top: -12px;
          display: flex;
          align-items: center;
          padding: 4px 11px;
          background: linear-gradient(270deg, #fe8d65 0%, #fe4d21 100%);
          border-radius: 9px 0px 9px 0px;
          img {
            width: 11px;
            height: 11px;
            display: block;
          }
          span {
            margin-left: 5px;
            font-size: 14px;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            color: #ffffff;
          }
        }
        .title {
          margin-top: 24px;
          font-size: 18px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          color: #333333;
          .sent {
            color: #fa6500;
          }
        }
        .date {
          margin-top: 8px;
          font-size: 14px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          color: #999999;
        }
        .price {
          margin-top: 4px;
          font-size: 36px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 600;
          color: #fa6500;
          span {
            &:first-child {
              font-size: 24px;
            }
          }
        }
        .old-price {
          margin-top: 6px;
          font-size: 18px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 400;
          color: #999999;
        }
        .text-through {
          text-decoration: line-through;
        }
        &-active {
          border-color: #f1423d;
          background: #fff2f2;
        }
      }
    }
    .type-row {
      display: flex;
      padding-top: 63px;
      display: flex;
      justify-content: center;
      .pay-type {
        display: flex;
        .card {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-right: 38px;
          .icon {
            width: 116px;
            height: 116px;
            border: 1px solid #93d375;
            display: flex;
            align-items: center;
            justify-content: center;
            img {
              width: 100px;
              height: 100px;
            }
          }
          .names {
            margin-top: 16px;
            display: flex;
            align-items: center;
            img {
              display: block;
              width: 17px;
              height: 15px;
            }
            span {
              margin-left: 5px;
              font-size: 14px;
              font-family: PingFang SC, PingFang SC;
              font-weight: 400;
              color: #666666;
            }
          }
          &:last-child {
            .icon {
              border-color: #05b6fc;
            }
            .names {
              img {
                width: 18px;
                height: 18px;
              }
            }
          }
        }
      }
      .price-info {
        .price {
          font-size: 36px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 600;
          color: #fa6500;
          span {
            &:first-child {
              font-size: 24px;
            }
          }
        }
        .old-price {
          margin-left: 8px;
          font-size: 16px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 400;
          color: #999999;
          position: relative;
          bottom: 10px;
          text-decoration: line-through;
        }
        .select {
          width: 262px;
          margin-top: 8px;
        }
        .tips {
          margin-top: 10px;
          font-size: 12px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          span {
            color: #666;
            &:last-child {
              cursor: pointer;
              color: #f1423d;
            }
          }
        }
      }
    }
    .vip-privilege {
      margin-top: 55px;
      display: flex;
      .label {
        display: flex;
        img {
          display: block;
          width: 20px;
          height: 17px;
        }
        span {
          margin-left: 6px;
          font-size: 14px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          color: #999999;
        }
      }
      .btns {
        margin-left: 26px;
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        gap: 16px 10px;
        .btn {
          font-size: 14px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          color: #333333;
          padding: 5px 10px;
          background: #f5f4f6;
          border-radius: 3px;
        }
      }
    }
  }
}
</style>
